#pragma once

#include <iostream>
#include <cstring>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <functional>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"

using namespace log_ns;
using namespace socket_ns;

static const int gsockfd = -1;
static const uint16_t glocalport = 8888;
static const int gblcklog = 8;

using service_io_t = std::function<void(SockSPtr, InetAddr &)>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

class TcpServer
{
public:
    TcpServer(service_io_t service, const uint16_t port = glocalport)
        : _listensockfd(std::make_shared<TcpSocket>()), _port(port), _isrunning(false), _service(service)
    {
        _listensockfd->BuildListenSocket(_port);
    }

    class ThreadData
    {
    public:
        ThreadData(TcpServer *self, SockSPtr sockfd, InetAddr &addr)
            : _self(self), _sockfd(sockfd), _addr(addr)
        {
        }
        ~ThreadData() {}

        TcpServer *_self;
        SockSPtr _sockfd;
        InetAddr _addr;
    };

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr client;
            SockSPtr newsock = _listensockfd->Accepter(&client);
            if (newsock == nullptr)
                continue;
            LOG(INFO, "get a new link, client info : %s, sockfd is : %d\n", client.AddrStr().c_str(), newsock->Sockfd());

            pthread_t tid;
            ThreadData *td = new ThreadData(this, newsock, client);
            pthread_create(&tid, nullptr, Excute, td); 
        }
        _isrunning = false;
    }

    static void *Excute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->_service(td->_sockfd, td->_addr);
        td->_sockfd->Close();
        delete td;
        return nullptr;
    }

    ~TcpServer() {}

private:
    SockSPtr _listensockfd;
    uint16_t _port;
    bool _isrunning;
    service_io_t _service;
};